package ewelinkapi

import (
	"context"
	"encoding/json"
	"fmt"

	"gitee.com/libs_2/ewelinkapi/constant"
	"gitee.com/libs_2/ewelinkapi/model"
	"github.com/rs/zerolog/log"
)

// 账号登录
func (c *Client) LoginAccount(ctx context.Context, req model.AccountLoginRequest) (model.LoginResult, error) {
	var lr model.LoginResponse
	body, err := json.Marshal(req)
	if err != nil {
		return lr.Data, err
	}

	bs, err := c.doPost(ctx, constant.URL_ACCOUNT_LOGIN, true, false, true, body)
	if err != nil {
		return lr.Data, err
	}

	err = json.Unmarshal(bs, &lr)
	if err != nil {
		return lr.Data, err
	}
	if lr.Code != constant.CODE_SUCCESS {
		return lr.Data, fmt.Errorf("code:%d,msg:%s", lr.Code, lr.Msg)
	}

	return lr.Data, nil
}

// 刷新token
func (c *Client) RefreshToken(ctx context.Context, refreshToken string) (model.RefreshTokenResult, error) {
	var lr model.RefreshTokenResponse

	var (
		needToken = false
		needSign  = true
	)

	if c.hackMode {
		needToken = true
		needSign = false
	}

	bs, err := c.doPost(ctx, constant.URL_TOKEN_REFRESH, true, needToken, needSign,
		[]byte(fmt.Sprintf(`{"rt":"%s"}`, refreshToken)))
	if err != nil {
		return lr.Data, err
	}

	err = json.Unmarshal(bs, &lr)
	if err != nil {
		return lr.Data, err
	}
	if lr.Code != constant.CODE_SUCCESS {
		return lr.Data, fmt.Errorf("code:%d,msg:%s", lr.Code, lr.Msg)
	}

	return lr.Data, nil
}

func (c *Client) refreshTokenWithHack(ctx context.Context, refreshToken string) (model.RefreshTokenResult, error) {
	var lr model.RefreshTokenResponse
	bs, err := c.doPost(ctx, constant.URL_TOKEN_REFRESH, true, true, false,
		[]byte(fmt.Sprintf(`{"rt":"%s"}`, refreshToken)))
	if err != nil {
		return lr.Data, err
	}

	err = json.Unmarshal(bs, &lr)
	if err != nil {
		return lr.Data, err
	}
	if lr.Code != constant.CODE_SUCCESS {
		return lr.Data, fmt.Errorf("code:%d,msg:%s", lr.Code, lr.Msg)
	}

	if len(lr.Data.AccessToken) > 0 {
		err = c.cache.SetAccessToken(ctx, constant.KEY_ACCESS_TOKEN, lr.Data.AccessToken)
		if err != nil {
			log.Error().Err(err).Msg("auto token failed on SetAccessToken")
		}

		err = c.cache.SetRefreshToken(ctx, constant.KEY_REFRESH_TOKEN, lr.Data.RefreshToken)
		if err != nil {
			log.Error().Err(err).Msg("auto token failed on SetAccessToken")
		}
	}

	return lr.Data, nil
}
